package com.itheima.service.db.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.domain.db.*;
import com.itheima.mapper.*;
import com.itheima.service.db.TestSoulService;
import com.itheima.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
@Slf4j
public class TestSoulServiceImpl implements TestSoulService {

    @Autowired
    private TopicMapper topicMapper;

    @Autowired
    private UserTopicMapper userTopicMapper;

    @Autowired
    private TopicQuestionMapper topicQuestionMapper;

    @Autowired
    private OptionMapper optionMapper;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private ReportDimensionMapper reportDimensionMapper;

    @Autowired
    private TopicResultMapper topicResultMapper;


    @Override
    public List<TopicVo> findAllQuestions(User LocalUser) {
        List<TopicVo> topicVos = new ArrayList<>();
        //查询所有题目
        List<Topic> topics = topicMapper.selectList(null);
        log.info("topicVos:{}", topics);
        for (Topic topic : topics) {
            //根据用户id查询题目是否锁住和报告id
            QueryWrapper<UserTopic> wrapper = new QueryWrapper<>();
            wrapper.eq("topic_id", topic.getId());
            ThreadLocal<User> user = new ThreadLocal<>();
            log.info("user:{}", user.get());
            wrapper.eq("user_id", LocalUser.getId());
            UserTopic userTopic = userTopicMapper.selectOne(wrapper);
            log.info("userTopic:{}", userTopic);
            TopicVo topicVo = new TopicVo();
            topicVo.setId(topic.getId());
            topicVo.setName(topic.getName());
            topicVo.setCover(topic.getCover());
            topicVo.setLevel(topic.getLevel());
            topicVo.setStar(topic.getStar());
            topicVo.setIsLock(userTopic.getIsLock());
            topicVo.setReportId(userTopic.getReportId());

            //查询题目下的所有问题
            List<QuestionsVo> questions = new ArrayList<>();
            List<TopicQuestion> topicQuestions = topicQuestionMapper.selectList(new QueryWrapper<TopicQuestion>().eq("topic_id", topic.getId()));
            log.info("topicQuestions:{}", topicQuestions);
            //遍历问题
            for (TopicQuestion topicQuestion : topicQuestions) {
                //查询每个问题的选项
                QuestionsVo questionsVo = new QuestionsVo();
                questionsVo.setId(String.valueOf(topicQuestion.getId()));
                questionsVo.setQuestion(topicQuestion.getQuestion());
                List<OptionsVo> options = new ArrayList<>();

                List<Option> questionId = optionMapper.selectOptionsByQuestionId(topicQuestion.getId());

                for (Option option : questionId) {
                    OptionsVo optionsVo = new OptionsVo();
                    optionsVo.setId(option.getId());
                    optionsVo.setOption(option.getOption());
                    options.add(optionsVo);
                    questionsVo.setOptions(options);
                }
                questions.add(questionsVo);

            }
            topicVo.setQuestions(questions);
            topicVos.add(topicVo);
        }
        return topicVos;
    }

    @Transactional
    public Integer answer(AnswersVo answers, User LocalUser) {
        //遍历答案，统计分数
        int score = 0;
        List<Integer> questionIds = new ArrayList<>();

        for (Answers answer : answers.getAnswers()) {
            Option option = optionMapper.selectOneById(answer.getOptionId());
            score += Integer.parseInt(option.getScore());
            questionIds.add(Integer.parseInt(answer.getQuestionId()));

        }
        //查询当前topicId
        TopicQuestion topicQuestion = topicQuestionMapper.selectOne(new QueryWrapper<TopicQuestion>().eq("id", questionIds.get(0)));
        int TopicId = Integer.parseInt(topicQuestion.getTopicId());
        //查询所有问题
        List<TopicQuestion> topicQuestions = topicQuestionMapper.selectList(new QueryWrapper<TopicQuestion>().eq("topic_id", TopicId));

        int userScore1 = 0;
        int maxScore1 = 0;

        int userScore2 = 0;
        int maxScore2 = 0;

        int userScore3 = 0;
        int maxScore3 = 0;

        int userScore4 = 0;
        int maxScore4 = 0;
        for (TopicQuestion allQuestion : topicQuestions) {
            //根据不同的问题类型进行处理
            switch (allQuestion.getCharacterType()) {
                case 1://抽象
                    List<Integer> dimensionRes1 = dimension(answers, allQuestion);
                    userScore1 += dimensionRes1.get(0);
                    maxScore1 += dimensionRes1.get(1);
                    break;
                case 2://理性
                    List<Integer> dimensionRes2 = dimension(answers, allQuestion);
                    userScore2 += dimensionRes2.get(0);
                    maxScore2 += dimensionRes2.get(1);
                    break;
                case 3://判断
                    List<Integer> dimensionRes3 = dimension(answers, allQuestion);
                    userScore3 += dimensionRes3.get(0);
                    maxScore3 += dimensionRes3.get(1);
                    break;
                case 4://外向
                    List<Integer> dimensionRes4 = dimension(answers, allQuestion);
                    userScore4 += dimensionRes4.get(0);
                    maxScore4 += dimensionRes4.get(1);
                    break;
            }
        }
        String formattedDimension1 = String.format("%.2f", userScore1 * 1.0 / maxScore1);
        String formattedDimension2 = String.format("%.2f", userScore2 * 1.0 / maxScore2);
        String formattedDimension3 = String.format("%.2f", userScore3 * 1.0 / maxScore3);
        String formattedDimension4 = String.format("%.2f", userScore4 * 1.0 / maxScore4);
        log.info("dimension1:{}", formattedDimension1);
        log.info("dimension2:{}", formattedDimension2);
        log.info("dimension3:{}", formattedDimension3);
        log.info("dimension4:{}", formattedDimension4);
        UserTopic userTopic = new UserTopic();
        //新增问卷报告
        Report report = new Report();
        report.setUserId(Math.toIntExact(LocalUser.getId()));
        report.setTopicId(TopicId);
        if (score < 21) {
            report.setTopicResultId(1);
        } else if (score <= 40) {
            report.setTopicResultId(2);
        } else if (score <= 55) {
            report.setTopicResultId(3);
        } else
            report.setTopicResultId(4);
        reportMapper.insert(report);
        Long insertId = report.getId();
        log.info("问卷报告Id:{}", insertId);
        //将得分存到user_Topic表中
        LambdaUpdateWrapper<UserTopic> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserTopic::getTopicId, TopicId)
                .eq(UserTopic::getUserId, LocalUser.getId())
                .set(UserTopic::getScore, score)
                .set(UserTopic::getReportId, insertId);
        userTopicMapper.update(userTopic, updateWrapper);
        //存储各维度占比

        reportDimensionMapper.inserTreportDimension(Math.toIntExact(insertId), 1, formattedDimension1);
        reportDimensionMapper.inserTreportDimension(Math.toIntExact(insertId), 2, formattedDimension2);
        reportDimensionMapper.inserTreportDimension(Math.toIntExact(insertId), 3, formattedDimension3);
        reportDimensionMapper.inserTreportDimension(Math.toIntExact(insertId), 4, formattedDimension4);

        //解锁下个问卷
        UserTopic nextUserTopic = userTopicMapper.selectOne(new QueryWrapper<UserTopic>()
                .eq("user_id", LocalUser.getId())
                .eq("topic_id", TopicId + 1));
        if (nextUserTopic != null) {
            nextUserTopic.setIsLock(0);
            userTopicMapper.update(nextUserTopic, new QueryWrapper<UserTopic>().eq("id", nextUserTopic.getId()));
        }
        return TopicId;
    }

    private List<Integer> dimension(AnswersVo answers, TopicQuestion allQuestion) {
        List<Option> options = optionMapper.selectOptionsByQuestionId(allQuestion.getId());
        int maxScore = 0;
        int userScore = 0;
        for (Option option : options) {
            //查询该问题最高得分
            if (Integer.parseInt(option.getScore()) > maxScore) {
                maxScore = Integer.parseInt(option.getScore());
            }

        }
        //查询该问题用户得分
        for (Answers answer : answers.getAnswers()) {
            log.info("用户答案:{}", answer);
            if (Integer.parseInt(answer.getQuestionId()) == allQuestion.getId()) {
                log.info("用户答案id:{}", answer.getQuestionId());
                userScore = Integer.parseInt(optionMapper.selectByQuestionIdAndId(answer.getQuestionId(), answer.getOptionId()).getScore());
            }
        }
        log.info("问题ID:{}", allQuestion.getId());
        log.info("maxScore:{},userScore:{}", maxScore, userScore);
        //计算该类型维度占比
        List<Integer> list = new ArrayList<>();
        list.add(userScore);
        list.add(maxScore);
        return list;
    }

    @Override
    public ReportVo report(Long id) {
        Report report = reportMapper.selectOne(new QueryWrapper<Report>().eq("id", id));
        ReportVo reportVo = new ReportVo();
        if (report != null) {
            List<DimensionsVo> dimensions = new ArrayList<>();
            TopicResult topicResult = topicResultMapper.selectOne(new QueryWrapper<TopicResult>()
                    .eq("id", report.getTopicResultId()));
            reportVo.setConclusion(topicResult.getCharacterType());
            reportVo.setCover(topicResult.getImg());
            List<ReportDimension> reportDimensionList = reportDimensionMapper.selectList(new QueryWrapper<ReportDimension>()
                    .eq("report_id", id));
            for (ReportDimension reportDimension : reportDimensionList) {
                DimensionsVo dimensionsVo = new DimensionsVo();
                if (reportDimension.getKey() == 1) {
                    dimensionsVo.setKey("抽象");
                } else if (reportDimension.getKey() == 2) {
                    dimensionsVo.setKey("理性");
                } else if (reportDimension.getKey() == 3) {
                    dimensionsVo.setKey("判断");
                } else if (reportDimension.getKey() == 4) {
                    dimensionsVo.setKey("外向");
                }
                dimensionsVo.setValue(Double.parseDouble(reportDimension.getValue()) * 100 + "%");
                dimensions.add(dimensionsVo);
            }
            reportVo.setDimensions(dimensions);

        }

        return reportVo;
    }
}
